﻿using System;
using System.Data.SqlClient;

namespace DesoutterTest
{
    class CurveHandler
    {
        /// <summary>
        /// SELECT CRV_CurveID id, CRV_ResultID resultId, CRV_PointDuration pointDuration, CRV_PointCount pointCount, CRV_CurveType curveType, CRV_TorqueThreshold torqueThreshold, CRV_BlobFormat blobFormat, CRV_Points points   FROM CURVE C ";
        /// </summary>
        /// <param name="resultId">RESULT表中的ID</param>
        /// <returns>Curve对象</returns>
        public Curve FetchCurveByResultID(int resultId)
        {
            string sqlQuery = $"{Context.CurveBasicSQL} WHERE C.CRV_ResultID = {resultId};";
            using (SqlConnection conn = new SqlConnection(Context.GetConnectionString()))
            {
                conn.Open();
                using (SqlCommand command = new SqlCommand(sqlQuery, conn))
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    Curve curve = new Curve();
                    if (reader.Read())
                    {
                        curve.Id = reader.GetInt32(reader.GetOrdinal("id"));
                        curve.ResultId = reader.GetInt32(reader.GetOrdinal("resultId"));
                        curve.PointDuration = reader.GetInt32(reader.GetOrdinal("pointDuration"));
                        curve.PointCount = reader.GetInt16(reader.GetOrdinal("pointCount"));
                        curve.CurveType = reader.GetInt16(reader.GetOrdinal("curveType"));
                        var torqueThresholdValue = reader["torqueThreshold"];
                        curve.TorqueThreshold = torqueThresholdValue != DBNull.Value ? Convert.ToDouble(torqueThresholdValue) : 0.0;
                        curve.BlobFormat = reader.GetInt16(reader.GetOrdinal("blobFormat"));
                        curve.Points = (byte[])reader["points"];
                    }
                    return curve;
                }
            }
        }
    }
}
